package com.zues.thread.safe_collection;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CurrentHashMapDemo
 * @Description 学习测试ConcurrentHashMap
 * @Author zeus
 * @Date 4/2/2025 2:28 下午
 * @Version 1.0
 **/
@Slf4j(topic = "c.ConcurrentHashMapDemo1")
public class ConcurrentHashMapDemo1 {

    public static void main(String[] args) throws InterruptedException {
        //基本操作：
        ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<String, Integer>();
        scores.put("Alice", 90);    // 线程安全的put操作
        scores.putIfAbsent("Bob", 85); // 不存在时添加
        log.debug("Bob's score: {}", scores.get("Bob"));

        //线程安全演示：
        ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<Integer, String>();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //并行添加100个
        for (int i = 0; i < 100; i++) {
            final int key = i;
            executorService.submit(() -> {
                map.put(key, "Value-" + key);
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
        log.debug("Map size: {}", map.size());

        //遍历方法
        map.forEach(2, (key, value) -> log.debug(String.valueOf(key), "{} = {}", value));

        //合并操作（原子的）
        scores.merge("Alice", 10, (oldValue, newValue) -> oldValue + newValue);
        log.debug("Alice's score: {}", scores.get("Alice"));

    }

}
